// pages/sugar_record/sugar_record.js
import config from '../../mars/conf/config'
var api = require("../../mars/services/api.js");

import sort from '../../mars/services/data.js';
import mainFood  from '../../mars/services/mainFood.js';
import milkAndEgg from '../../mars/services/milkAndEgg.js';
import vagatable from '../../mars/services/vagetable.js';
import oil from '../../mars/services/oil.js';
import utils from "../../mars/services/utils.js";

var that;
var app = getApp();
var deltaX = 0;
var minValue = 1;

var time = 0;
var touchDot = 0; //触摸时的原点
var interval = "";
var flag_hd = true;

Page({
  data: {
    animationFoot: {},
    animationContent: {},
    isIphoneX: false,
    target: 500, //kcal
    totalWeight: 0,
    totalEnergy: 0,
    previewTotalEnergy: 0,
    weight: 50,
    kcal: 100,

    isshow: true,
    showOverlay: false,
    mealActive: "breakfast",
    foodType: "mainFood",
    menuActiveIdx: 0,
    scrollIntoViewId:"",
    sorts: sort,
    meal: {
      breakfast: {
        mainFood: [],
        milkAndEgg: [],
        vagatable: [],
        oil: []
      },
      lunch: {
        mainFood: [],
        milkAndEgg: [],
        vagatable: [],
        oil: []
      },
      supper: {
        mainFood: [],
        milkAndEgg: [],
        vagatable: [],
        oil: []
      } 
    },

    mainFood: mainFood,
    milkAndEgg: milkAndEgg,
    vagatable: vagatable,
    oil: oil,

    foodList: [],
    currentEditIndex: 0,
    currentMeasureIndex: -1,
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    // options = {
    //   foodType: "oil",
    //   meal: "breakfast",
    //   target: 500,
    // };

   
    var mealData = wx.getStorageSync(options.meal);
    var data = {};
    var nullMeal = {
      mainFood: [],
      milkAndEgg: [],
      vagatable: [],
      oil: []
    };
    that.data.meal[options.meal] = mealData || nullMeal;
    data.meal = that.data.meal;
    data.mealActive = options.meal;
    data.foodType = options.foodType;
    data.target = options.target || 500;

    data.isIphoneX = app.globalData.isIphoneX;
    data.totalEnergy = that.data.meal[options.meal][options.foodType].reduce((pre, now) => {
      return {
        kcal: now.kcal += pre.kcal
      };
    }, {
      kcal: 0
    }).kcal;

    this.setData(data);
    this.getFoodListByType(0);
  },
  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    flag_hd = true; //重新进入页面之后，可以再次执行滑动切换页面代码
    clearInterval(interval); // 清除setInterval
    time = 0;
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  removeSelectFood(e) {
    let index = e.currentTarget.dataset.index;
    let meal = that.data.meal;
    let foodSelectList = meal[that.data.mealActive][that.data.foodType];
    foodSelectList.splice(index, 1);

    // 刷新总卡路里
    let totalEnergy = 0,
      totalWeight = 0;
    foodSelectList.forEach((item) => {
      totalWeight += parseInt(item.weight);
      totalEnergy += parseInt(item.kcal);
    });

    that.setData({
      totalWeight: totalWeight,
      totalEnergy: totalEnergy,
      meal: meal,
    });
  },
  hideOverlay() {
    that.setData({
      showOverlay: false,
    });
  },
  showTap(e) {
    let index = e.currentTarget.dataset.index;
    // show index tap

  },
  showAddFoodPanel(e) {
    let index = -1;
    let foodSelectList = that.data.meal[that.data.mealActive][that.data.foodType];
    let foodList = that.data.foodList;
    let weight = 0;

    if (e.currentTarget.dataset.index == -1) {
      // from selected list
      index = e.currentTarget.dataset.selectindex;
      let f_id = foodSelectList[index].f_id;
      weight = foodSelectList[index].weight;

      foodList.some((item, idx) => {
        if (item.f_id == f_id) {
          index = idx
          return true;
        }
        return false;
      });

    } else {
      // from foodList
      index = e.currentTarget.dataset.index;
      let currentFood = that.data.foodList[index];
      foodSelectList.some((item, index) => {
        if (item.f_id == currentFood.f_id) {
          weight = foodSelectList[index].weight
          return true;
        }
        return false;
      });
    }

    if (index == -1) {
      wx.showToast({
        title: '没有当前食物信息',
        icon: 'none',
        duration: 1200
      })
      return;
    }
    that.setData({
      currentEditIndex: index,
      showOverlay: true,
      weight: weight,
      currentMeasureIndex: -1,
      previewTotalEnergy: that.data.totalEnergy
    });
  },
  getFoodListByType(index) {
    let c_id = "";
    let menuList = that.data.sorts[that.data.foodType];
    let foodList = that.data[that.data.foodType];
    that.setData({
      foodList: foodList
    });
  },
  bindRangeValue(e) {
    let weight, index;
    let foodSelectList = that.data.meal[that.data.mealActive][that.data.foodType];
    let currentFood = that.data.foodList[that.data.currentEditIndex];

    if (e.currentTarget.dataset.index == -1) {
      // from slide 
      index = e.currentTarget.dataset.index;
      weight = e.detail.value;
    } else {
      // from click
      index = e.currentTarget.dataset.index;
      weight = e.currentTarget.dataset.weight;
    }

    // 计算和总卡路里差值
    let curFoodEnergy = weight / 100 * parseInt(currentFood.energy_kcal);
    curFoodEnergy = parseInt(curFoodEnergy);

    // 判断是否已有该食物
    let idx = -1;
    foodSelectList.some((item, index) => {
      if (item.f_id == currentFood.f_id) {
        idx = index;
        return true;
      }
      return false;
    });
    if (idx != -1) {
      foodSelectList[idx].weight = weight,
        foodSelectList[idx].kcal = curFoodEnergy;
    } else {
      foodSelectList.push({
        f_name: currentFood.f_name,
        f_id: currentFood.f_id,
        weight: weight,
        kcal: curFoodEnergy,
        pic_url: currentFood.pic_url,
      });
    }

    // 更新差值
    let totalEnergy = 0;
    foodSelectList.forEach((item) => {
      totalEnergy += parseInt(item.kcal);
    });
    that.setData({
      kcal: curFoodEnergy,
      weight: weight,
      previewTotalEnergy: totalEnergy,
      currentMeasureIndex: index
    })
  },
  bindAddToCart(e) {
    let meal = that.data.meal;
    let foodSelectList = meal[that.data.mealActive][that.data.foodType];
    let currentFood = that.data.foodList[that.data.currentEditIndex];
    let kcal = that.data.kcal;
    let weight = that.data.weight;

    // 判断是否已有该食物
    let idx = -1;
    foodSelectList.forEach((item, index) => {
      if (item.f_id == currentFood.f_id) {
        idx = index;
      }
    })
    if (idx != -1) {
      foodSelectList[idx].weight = weight,
        foodSelectList[idx].kcal = kcal;
    } else {
      foodSelectList.push({
        f_name: currentFood.f_name,
        f_id: currentFood.f_id,
        pic_url: currentFood.pic_url,
        weight: weight,
        kcal: kcal
      });
    }

    // 更新总卡路里
    let totalEnergy = 0,
      totalWeight = 0;
    foodSelectList.forEach((item) => {
      totalWeight += parseInt(item.weight);
      totalEnergy += parseInt(item.kcal);
    });

    that.setData({
      totalWeight: totalWeight,
      totalEnergy: totalEnergy,
      previewTotalEnergy: totalEnergy,
      meal: meal,
      showOverlay: false,
    });
  },
  setToLocalStoage() {
    let currentMeal = that.data.meal[that.data.mealActive];
    try {
      wx.setStorageSync(that.data.mealActive, currentMeal);
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1200
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1200)
    } catch (e) {
      wx.showToast({
        title: '保存出错',
        icon: 'none',
        duration: 1200
      })
    }
  },
  displayFoodSelectList(e) {
    let isshow = e.currentTarget.dataset.isshow;
    // to hide
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.animation = animation
    if (isshow) {
      // to hide
      animation.height(0).step();
      this.setData({
        animationFoot: animation.export(),
        isshow: false
      })
    } else {
      // to show
      animation.height(41 + 46 * that.data.meal[that.data.mealActive][that.data.foodType].length).step();
      this.setData({
        animationFoot: animation.export(),
        isshow: true
      })
    }
  },
  asyncMenuActiveIdx(e) {
    
      let index = e.currentTarget.dataset.index;
      if(index!=null && index!=undefined){
        let scrollIntoViewId = that.data.scrollIntoViewId;
        // 点击nav
        for (let idx = 0, length = that.data[that.data.foodType].length; idx < length; idx++) {
          if (that.data[that.data.foodType][idx].sortName == that.data.sorts[that.data.foodType][index].c_name) {
            scrollIntoViewId = "view_" + that.data[that.data.foodType][idx].f_id;
            break;
          }
        }

        that.setData({
          scrollIntoViewId: scrollIntoViewId,
          menuActiveIdx: index
        });
    }else{
        // 通过e.detail.scrollTop 计算index
        let scrollTop = e.detail.scrollTop;
        console.log(scrollTop, utils);
        index = utils.getScrollTopPixel(that.data.foodType, scrollTop);
        that.setData({
          menuActiveIdx: index
        });
    }
  }
})